package iterator.v3;

public class LinkedList_<T> implements Collection_<T> {
    Node<T> head = null;
    Node<T> tail = null;
    int size = 0;

    @Override
    public void add(T obj) {
        Node<T> node = new Node<>();
        node.data = obj;
        node.next = null;
        if (head == null) {
            head = tail = node;
            ++size;
        } else {
            tail.next = node;
            tail = node;
            ++size;
        }
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator_<T> iterator() {
        return new LinkedListIterator_<T>();
    }

    private class Node<T> {
        T data;
        Node next;
    }

    private class LinkedListIterator_<T> implements Iterator_<T> {
        Node<T> current = (Node<T>) head;

        @Override
        public T next() {
            T data = current.data;
            current = current.next;
            return data;
        }

        @Override
        public boolean hasNext() {
            return current != null;
        }
    }
}
